use tauri::AppHandle;

use crate::{
    app_config::{get_config_file_path, AppConfig, Storage},
    shortcut_manage,
};

#[tauri::command]
pub fn get_config(state: tauri::State<Storage>) -> Result<AppConfig, &str> {
    let app_config = state.app_config.lock().map_err(|_| "获取配置文件失败")?;
    Ok(app_config.clone())
}

#[tauri::command]
pub fn set_config(
    state: tauri::State<Storage>,
    app_config: AppConfig,
    app_handle: AppHandle,
) -> Result<(), &str> {
    shortcut_manage::init(&app_handle, &app_config).map_err(|_| "快捷键注册失败")?;
    let config_file_path = get_config_file_path(&app_handle).map_err(|_| "获取配置文件路径失败")?;
    app_config
        .clone()
        .save_to_file(config_file_path.to_str().ok_or("")?)
        .map_err(|_| "配置文件路径转换失败")?;
    *state.app_config.lock().map_err(|_| "保存配置失败")? = app_config;
    Ok(())
}
